require("sys")
local dble = {}
sendData=false
local dataLen=18
local function BleInit()
    -- 监听GATT服务器的WRITE_CHR, 也就是收取数据的回调
    sys.subscribe("BLE_GATT_WRITE_CHR", function(info, data)
        log.info("ble", "data got!!", data)
        local s,a = unpack(string.split(data,',',false))
        log.info(s,a)
        sys.publish("ddn_event", {src = "dble",evt = "COMMAND", dat = {speed=s+0,angle=a+0}}) 
    end)    
    if nimble.setUUID then -- 2023-02-25之后编译的固件支持本API
        nimble.setUUID("srv", string.fromHex("e0fe"))      -- 服务主UUID         ,  
        nimble.setUUID("write", string.fromHex("e2fe"))    -- 往本设备写数据的UUID,  
        nimble.setUUID("indicate", string.fromHex("e1fe")) -- 订阅本设备的数据的UUID,
    end    
    sys.wait(2000)
    nimble.init("DdnBlePaoCar")
    sys.wait(2000)
end

local function BleMain()
    log.info("--------------------BleMain--------------------------")
    BleInit();
    while true do
        local ret,dat = sys.waitUntil("ddn_event")
        if(ret==true) then
            if (dat.src == "dsec" and dat.evt == "HEART") then
                -- log.info("------dble 心跳到来------")
                if  not sendData and nimble.connok() then
                    nimble.send_msg(1, 0,string.format("{\"heart\":%06d}",dat.dat.heart))
                end
            end   
            -- rfid數據到來
            if(dat.src== "dcom" and dat.evt=="DATA") then
                if nimble.connok() then
                    sendData=true
                    local  send = string.format("{\"data\":\"%s\"}",dat.dat)
                    local  slen = string.len(send)
                    local   part = slen//dataLen
                    local   left = slen%dataLen
                    log.info("slen",slen,"part",part,"left",left)
                    local temp=nil
                    local start=0
                    for i = 0,part do
                        temp = string.sub(send,start,start+dataLen)
                        start=start+dataLen+1 
                        -- log.info("send before")
                        while  not nimble.send_msg(1, 0,temp) do
                            log.info("send fail retry")
                            sys.wait(10) 
                        end 
                        -- log.info("after send",temp)
                            -- sys.wait(2) 
                    end
                    sendData=false
                    -- temp = string.sub(send,part*20)
                    -- 通過藍牙發給安卓端
                    -- nimble.send_msg(1, 0,send)
                    -- sys.wait(10)
                end
            end         
        end
    end
end

local function Init()
    sys.taskInit(BleMain)
end
dble.Init = Init
return dble

